package com.lzyjkz.quick_auth.util;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.lzyjkz.quick_components.constant.oauth.GithubOAuthConstant;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.protocol.HTTP;
import org.springframework.web.client.RestTemplate;

import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;

public class OAuth2Util {
    public static String getAccessToken(Class<?> clazz, String code, String state) throws NoSuchFieldException, IllegalAccessException {
        String clientID = (String) clazz.getField("ClientID").get(null);
        String clientSecret = (String) clazz.getField("ClientSecret").get(null);
        String grantType = (String) clazz.getField("GrantType").get(null);
        String redirectUri = (String) clazz.getDeclaredField("RedirectUri").get(null);

        HttpRequest tokenUri = HttpRequest
                .post(clazz.getDeclaredField("TokenUri").get(null).toString() +
                        "?client_id=" + clientID +
                        "&client_secret=" + clientSecret +
                        "&grant_type=" + grantType +
                        "&redirect_uri=" + redirectUri +
                        "&code=" + code
                );
        HttpResponse response = tokenUri
                .execute();
        return response.body();
    }

    public static String genericGetUserInfo(Class<?> clazz, String accessToken, String scope, String grantType) throws NoSuchFieldException, IllegalAccessException {
        HttpRequest userInfoUri = HttpRequest
                .get(clazz.getDeclaredField("UserInfoUri").get(null).toString() +
                        "?access_token=" + accessToken +
                        "&scope=" + scope +
                        "&grant_type=" + grantType
                );
        HttpResponse response = userInfoUri
                .execute();
        response.close();
        if (response.getStatus() != 200) {
            return null;
        }
        return response.body();
    }

    public static String getGitHubUserInfo(String accessToken, String scope, String tokenType) {
        Map<String, String> headers = new HashMap<>();

        headers.put("Accept", "application/vnd.github+json");
        headers.put("Authorization", "Bearer " + accessToken);
        headers.put("X-GitHub-Api-Version", "2022-11-28");

        HttpRequest userInfoUri = HttpRequest
                .get(GithubOAuthConstant.UserInfoUri)
                .addHeaders(headers);
        HttpResponse response = userInfoUri
                .execute();
        response.close();
        if (response.getStatus() != 200) {
            return null;
        }
        return response.body();
    }
}
